package com.cgbl.cg.vm.mine

import android.app.Application
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import api.ShopServiceFactory
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.model.CouponBean
import com.robot.base.model.PageListBean
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class PersonalCouponViewModel(application: Application) : GLBaseViewModel(application) {

    val uc = UiChangeEvent()

    val tabType = ObservableInt(TAB_UN_USE)

    val tabUnUse = ObservableField("未使用")

    val tabUsed = ObservableField("已使用")

    val tabInvalid = ObservableField("已过期")

    var page = 1

    var pageSize = 10

    val clickSelectUnUse = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_UN_USE)
        uc.changeTabEvent.postValue(TAB_UN_USE)
        refresh()
    })

    val clickSelectUsed = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_USED)
        uc.changeTabEvent.postValue(TAB_USED)
        refresh()
    })

    val clickSelectInvalid = BindingCommand<Any>(BindingAction {
        tabType.set(TAB_INVALID)
        uc.changeTabEvent.postValue(TAB_INVALID)
        refresh()
    })

    class UiChangeEvent {

        val changeTabEvent: SingleLiveEvent<Int> = SingleLiveEvent()

        val refreshCouponEvent: SingleLiveEvent<List<CouponBean>> = SingleLiveEvent()

        val loadMoreCouponEvent: SingleLiveEvent<List<CouponBean>> = SingleLiveEvent()

    }

    fun refresh() {
        page = 1
        queryCoupon()
    }

    fun loadMore() {
        page++
        queryCoupon()
    }

    fun queryCoupon() {
        val params = mapOf("status" to tabType.get(), "pageNo" to page, "pageSize" to pageSize)
        ShopServiceFactory.userCouponPage(params).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<CouponBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<CouponBean>>) {
                uc.refreshCouponEvent.postValue(t.data.list)
            }
        })
    }


    companion object {

        const val TAB_UN_USE = 0

        const val TAB_USED = 1

        const val TAB_INVALID = 2

    }


}